import React, { useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Grid, Typography, Button, Avatar } from '@material-ui/core';
import { Section, SectionAlternate } from 'components/organisms';
import { Hero, Users, Speakers, Banner } from './components';
import { useSelector, useDispatch } from 'react-redux'
import { callGetApi } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  content: {
    backgroundColor: theme.palette.alternate.main
  },
  loadMore: {
    height: '100px',
    backgroundColor: theme.palette.alternate.main
  },
  loadMoreButton: {
    backgroundColor: theme.palette.alternate.main,
    marginBottom: '50px',
    marginTop: '-30px'
  },
  sectionBreadcrumb: {
    '& .section-alternate__content': {
      paddingTop: theme.spacing(2),
      paddingBottom: theme.spacing(2),
    },
  },
  pagePaddingTop: {
    paddingTop: theme.spacing(3),
    [theme.breakpoints.up('md')]: {
      paddingTop: theme.spacing(5),
    },
  },
  center: {
    minWidth: '100%',
    maxWidth: '100%',
    [theme.breakpoints.up('sm')]: {
        minWidth: 420,
    },
  },
  toolBar: {
    marginTop: '30px',
  },
  usersSection: {
    marginTop: '-7%',
  },
  voteButton: {
    margin: '10px',
    backgroundColor: '#4051b5', 
    color: '#FFFFFF'
  },
  votingButton: {
    margin: '10px',
    backgroundColor: '#6b096b', 
    color: '#FFFFFF'
  },
}));

const Members = () => {
  const classes = useStyles();
  const dispatch = useDispatch();
  
  const searchKeyword = useSelector((state) => state.searchMembers.searchKeyword)
  const [userList, setUserList] = useState([]);
  const [categories, setCategories] = useState([]);
  const [category, setCategory] = useState(0);
  const [voting, setVoting] = useState(null);

  useEffect(() => {
    loadCategories();
  }, [])

  useEffect(() => {
    loadData()
  }, [searchKeyword, category])

  const loadCategories = async () => {
    callGetApi('vote/categories', dispatch, (data) => {
      setCategories(data)
      if (data.length) {
        setCategory(data[0].id)
      }
    })
  }

  const loadData = async () => {
    callGetApi(`vote/search_artists?category=${category}&search_key=${searchKeyword}&limit=20&offset=0`, dispatch, (data) => {
      if (checkContainsVotedArtist(data.data, data.user_voting)) {
        setUserList(data.data)
      }
      else {
        if (data.user_voting && data.user_voting.artist) {
          setUserList([data.user_voting.artist].concat(data.data));
        }
        else {
          setUserList(data.data)
        }
      }
  
      setVoting(data.user_voting);
    })
  }

  const checkContainsVotedArtist = (artists, voting) => {
    if (!voting) {
      return false;
    }

    for (const item of artists) {
      if (item.id == voting.artist_id) {
        return true;
      }
    }
    return false;
  }

  const loadMoreData = async () => {
    callGetApi(`vote/search_artists?category=${category}&search_key=${searchKeyword}&limit=20&offset=${userList.length}`, dispatch, (data) => {
      const newList = [...userList, ...data.data];
      setUserList(newList)
    })
  }

  return (
    <div className={classes.content}>
      <Banner />
      <Hero />
      <Grid item xs={12} container justifyContent="center" style={{marginTop: '20px'}}>
        {categories.map((item, index) => (
          <Button
            variant="contained"
            color="primary"
            size="large"
            onClick={() => {
              setCategory(item.id)
            }}
            className={category==item.id?classes.votingButton:classes.voteButton}
          >
            {item.title}
          </Button>
        ))}
       </Grid>
      <SectionAlternate>
        <Users data={userList} voting={voting} setVoting={setVoting} className={classes.usersSection}/>
      </SectionAlternate>
      <div className={classes.loadMore}>
        <Grid item xs={12} container justifyContent="center" className={classes.loadMoreButton}>
          <Button
            variant="contained"
            color="primary"
            size="large"
            onClick={loadMoreData}
            className={classes.button}
          >
            Load more
          </Button>
        </Grid>
      </div>
    </div>
  );
};

export default Members;
